#!/usr/bin/python

import pymongo

dbclient = pymongo.MongoClient()
db = dbclient.stock
price = db.price

def get_stockinfo(codelist):
    import urllib2
    url = 'http://hq.sinajs.cn/list=' + ','.join(codelist)

    page = urllib2.urlopen(url)
    lines = page.readlines()
    page.close()

    import re
    infos = []
    for line in lines:
        m = re.search('(.+)="(.+)"', line)
        items = m.group(2).split(',')
        info = {
             'code' : m.group(1)[-6:],
             'name'   : unicode(items[0], 'gb2312'),
             'curr'   : float(items[3]),
             'last'   : float(items[2]),
             'open'   : float(items[1]),
             'delta'  : float(items[3]) - float(items[2]),
             'low'    : float(items[5]),
             'high'   : float(items[4]),
             'buy'    : float(items[6]),
             'sell'   : float(items[7]),
             'volumn' : int(float(items[8]) / 100),
             'amount' : int(float(items[9]) / 10000) }

        if info['curr'] == 0 or info['curr'] == info['last']:
            info['percent'] = 0
        else:
            info['percent'] = (info['curr'] - info['last']) / info['last'] * 100
        infos.append(info)

    return infos


# -------- main --------
import time

codelist = [
            'sh000001',
            'sh600016',
            'sh600028',
            'sh600030',
            'sh600675',
            'sh601009',
            'sh601318',
            'sh601519',

            'sz000002',
            'sz000418',
            'sz000562',
            'sz000725',
            'sz002024',
            'sz300007',
            'sz300033',
            'sz300059',
            'sz399006',
            'sz399005',

            'sz399001',
            'sz000333'
            ]


from bottle import Bottle, run, template

app = Bottle()

@app.route('/stock/')
def stock():
    return template('stock', stockinfo=get_stockinfo(codelist))


@app.route('/stock/<code>')
def stockdetail(code):
    import json

    rows = price.find({ '_id' : {'$regex' : code} })
    if rows.count() == 0:
        return template('<B>Wrong code {{code}}</B>', code=code)

    else:
        lines = []
        for row in rows:
            lines.append(json.dumps(row))

        return '<br>'.join(lines)


run(app, host='localhost', port=9090)

